<?php
/************************FoxPHP威客系统************************/
/*                                                            */
/*  FoxPHP.Com (C)2006-2016 FoxPHP Inc.                       */
/*  This is NOT a freeware, use is subject to license terms   */
/*  FoxPHP威客系统是商业软件,使用于商业用途请购买授权         */
/*  V3.0 2016.3                                               */
/*  foxphp@aliyun.com                                         */
/*  http://www.foxphp.com                                     */
/*                                                            */
/**************************************************************/

if(!defined('IN_FOXPHP')) {
	exit('Data error');
}

//FoxPHP备份SQL
class BackupSQL{
	
	public $DataList;
	
	public function IsMysqlTableName($table=''){
		 
		$model = M();
		 
		$result=$model->query('SHOW TABLE STATUS FROM '.C('DB_NAME').' WHERE Name=\''.$table.'\'');
		  
		$num_rows = count($result);
  
		if($num_rows>0){ 
			return $num_rows;
		}else{
			return false;
		}
		   
	}

	public function ShowMysqlTable($table=''){
		$model = M();
	    return $model->query("SHOW CREATE TABLE ".$table);
	}
	
	public function SaveTable($tablearray,$backupname,$filesize){

		  error_reporting(0);
		  set_time_limit(0);
		  $times =@date("Ymd");
		  $filedir=C('S_BACKUP_DIR').'/'.$times;
		  if(!is_dir($filedir)) {
			    @mkdir($filedir,0777);  
			    WriteFile($filedir.'/index.html','');
		  }
		  
		  $backuplength=$filesize*1024;
		 
		  $TableStatus='-- FoxPHP威客系统'."\n";
          $TableStatus.='-- Version 3.0'."\n";
		  $TableStatus.='-- 2006-'.@date("Y").' 版权所有'."\n";
          $TableStatus.='-- http://www.foxphp.com'."\n";
		  $TableStatus.='-- 字符集 '.C('S_CHARSET')."\n";
		  $backupdate=date("Y 年 m 月 d 日 H:i:s");
          $TableStatus.='-- 生成日期: '.$backupdate."\n\n";
          
		  $TableInfo=$TableStatus;
		  
		  $backuptablename='';
		  
		  $newtablename='';

		  foreach($tablearray as $value){

			   if($backuptablename){
				    $backuptablename.=','.$value;
			   }else{
				    $newtablename=$backuptablename=$value;
			   }
			   
			   $TableInfo.='DROP TABLE IF EXISTS '.$value.';'."\n";
					 
			   if($this->IsMysqlTableName($value)){
		             
			         $ShowCreateTable=$this->ShowMysqlTable($value);
                     
					 if($ShowCreateTable){
						   foreach($ShowCreateTable as $value){
							   
								$TableInfo.=$value['create table'].';'."\n";
								$TableInfo.="\n";
						   
						   }
					 }

			   }
		  }
		  
		  $Tablewfile=$filedir.'/'.$backupname.'_0.sql';	
		  WriteFile($Tablewfile,$TableInfo);
		  
		  $backupinfo='0|'.$newtablename.'|'.$backupname.'|'.$filesize.'|'.$backuptablename;
		  
		  WriteFile(C('S_BACKUP_DIR').'/backup_'.$times.'.txt',$backupinfo);
		  
		  unset($TableInfo);
		  unset($TableDatas); 
		  unset($TableStatus);
		  
	}
	
	public function SaveTableData($Number=1,$RowSQL=0){
          
		  error_reporting(0);
		  set_time_limit(0);
		  
		  $times =@date("Ymd");
		  
		  $filedir=C('S_BACKUP_DIR').'/'.$times;
		  
		 
		  if(file_exists(C('S_BACKUP_DIR').'/backup_'.$times.'.txt')){
                   
				  $backupinfo=GetFile(C('S_BACKUP_DIR').'/backup_'.$times.'.txt');
				  
				  $backupinfoarray=explode('|',$backupinfo);
				  
				  if(!empty($backupinfoarray[1])){
						   
						   $wfile=$filedir.'/'.$backupinfoarray[2].'_'.$Number.'.sql';	
							
						   if($this->GetBackupDataList($Number,$backupinfoarray,$RowSQL)){
							   
								 $openwrite = @fopen($wfile,"a");
								 fwrite($openwrite,$this->DataList);
								 fclose($openwrite);
								
						   }else{
							   
								$openwrite = @fopen($wfile,"a");
								fwrite($openwrite,$this->DataList);
								fclose($openwrite);
								
								$this->NextBackupName($Number,$backupinfoarray);
								$this->SaveTableData($Number);
						
						   }
							
						   
						   return $Number+=1;
						   
				  }else{
						 
						 DelFile(C('S_BACKUP_DIR').'/backup_'.$times.'.txt');
						
						 return 'ok';
						 
				  }
	
		  
		  }else{

				return 'ok';
		  }
	
	}
	
	
	
    public function GetBackupDataList($Number,$backupinfoarray,$RowSQL){
	         
			$DataRows=100;
			 
	        $times =@date("Ymd");
		  
		    $filedir=C('S_BACKUP_DIR').'/'.$times;
	
			$value=str_replace(C('DB_PREFIX'),'',$backupinfoarray[1]);

			$tablearray=explode(',',$backupinfoarray[4]);
			
			$Rows=M($value)->count();
			
			if($Rows){
					
					WriteFile($filedir.'/'.$backupinfoarray[2].'_'.$Number.'.sql','');
					
					$NowRows=intval(@ceil($Rows/$DataRows));
					
					if($NowRows){
						 $fornum=$NowRows;
					}else{
						 $fornum=1;
					}
					
			
					if(!$RowSQL){
						$RowSQL=intval($backupinfoarray[0]);
					}
					
					$filelen=0;
					
					
					$nextbackup=0;
					

					for($i=0;$i<$fornum;$i++){

						  $StartRows=($i*$DataRows)+$RowSQL;
						  
						  $this->DataList.=$this->GetMakeMysqlDataList($value,$StartRows,$DataRows);
						  
						  $filelen=iconv_strlen($this->DataList,C('S_CHARSET'));
						  
						  if($filelen>=(intval($backupinfoarray[3])*1024)){
							  
								 $backupinfo=$StartRows+$DataRows.'|'.$backupinfoarray[1].'|'.$backupinfoarray[2].'|'.$backupinfoarray[3].'|'.$backupinfoarray[4];
									   
								 WriteFile(C('S_BACKUP_DIR').'/backup_'.$times.'.txt',$backupinfo);
								 
								 $nextbackup=1;
								 
								 break;
						  }
					}
					
					if($nextbackup){

						 return true;
					
					}else{
						
						 return false;
					
					}
					  
			 }else{
				   return false;
			 }
			 
	}
					  
	// 二维数组 | 表名 | 删除字段 | 替换值
	public function MakeMysqlInsert($tablearr=array(),$tablename,$dalete='',$replacearr=''){
		
		   if($tablearr){
		   
				$valuelist='';	
				
				foreach($tablearr as $value){	
				
					  $valuelist.='INSERT INTO '.C('DB_PREFIX').$tablename.'(';
					  
					  $keydata='';
					  $valuedata='';
					  
					  foreach($value as $key=>$val){	
							  
							  if($dalete!=$key){
									  if($keydata){
											$keydata.=',`'.$key.'`';
									  }else{
											$keydata.='`'.$key.'`';
									  }
									  
									  if($replacearr){
										    
											foreach($replacearr as $keyre=>$valuere){
												   
												   if($key==$keyre){
													   
													     $val=$valuere;
														 
												   }
												
											}
									  }
									  
									  if($valuedata){
											$valuedata.=',\''.str_replace('INSERT INTO','insert into',str_replace("'",'&#039;',$val)).'\'';
									  }else{
											$valuedata.='\''.str_replace('INSERT INTO','insert into',str_replace("'",'&#039;',$val)).'\'';
									  }
							  }
					  }
					  
					  $valuelist.=$keydata.')VALUES('.$valuedata.');'."\n";

				}
					  
				unset($tablearr);   
				
				return $valuelist;

		  }else{
			  
			    return false;
		  }
		
	}
	
	
	public function GetMakeMysqlDataList($tablename,$StartRows,$DataRows){
		
		$tabledataarray=M($tablename)->limit("$StartRows,$DataRows")->select();

		if($tabledataarray){

			return $this->MakeMysqlInsert($tabledataarray,$tablename);

		}else{

			return false;
		}
	}
	
	public function NextBackupName($Number,$backupinfoarray){
		
			$nowtable=str_replace(C('DB_PREFIX'),'',$backupinfoarray[1]);
			
			$tablearray=explode(',',$backupinfoarray[4]);
		    
			$times =@date("Ymd");
			
			$newtable='';
			foreach($tablearray as $key=>$value){
		
				    if($value==(C('DB_PREFIX').$nowtable)){
						  $id=$key+1;
						  $newtable=@$tablearray[$id];
					}
				
			}

			if(!empty($newtable)){
			     
				  $backupinfo='0|'.$newtable.'|'.$backupinfoarray[2].'|'.$backupinfoarray[3].'|'.$backupinfoarray[4];

				  WriteFile(C('S_BACKUP_DIR').'/backup_'.$times.'.txt',$backupinfo);
				
			}else{
				  DelFile(C('S_BACKUP_DIR').'/backup_'.$times.'.txt');
			}
		    
	}
	
}

 
?>